package com.dabai.simpleconnection;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dabai.dbutils.data.Patterns;
import com.dabai.dbutils.dialog.MdcDialog;
import com.dabai.dbutils.dialog.TipAlertDialog;
import com.dabai.dbutils.qrcode.QRCodeUtils;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.DateUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.NotificationUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.StringUtils;
import com.dabai.dbutils.utils.component.ActivityUtils;
import com.dabai.simpleconnection.adapter.ChatAdapter;
import com.dabai.simpleconnection.bean.ChatModel;
import com.dabai.simpleconnection.utils.DialogUtils;
import com.dabai.simpleconnection.utils.SendFileUtils;
import com.dabai.uitools.utils.ViewUtils;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.permissionx.guolindev.PermissionX;
import com.zhihu.matisse.Matisse;

import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;

public class MainActivity extends AppCompatActivity {

    Context context;
    private Socket client, client2;
    private TextView mRoomname;
    private EditText mChatEdittext;
    private ImageButton mSendtext;
    private RecyclerView mRecyclerview;

    private ChatAdapter chatAdapter;
    private LinearLayoutManager linearLayoutManager;
    private ImageButton mSendfile;

    private boolean isRunForground;

    private long senseyTime = 0;
    private long itemClickTime = 0;
    private ArrayList<String> photoList;
    private Chip mChip1;
    private Chip mChip2;
    private Chip mChip3;
    private Chip mChip4;
    private Chip mChip5;


    private SQLiteDatabase db;


    @Override
    protected void onPause() {
        super.onPause();
        isRunForground = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isRunForground = true;

    }


    private DatagramSocket udpSocket = null;
    private InetAddress udpServerAddress = null;

    private boolean isLink = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();

        context = this;
        SharedPreferencesBasicUse.init(context);

        //数据库创建与初始化
        db = openOrCreateDatabase("IpRecords", Context.MODE_PRIVATE, null);
        String create = "create table if not exists IpRecord(id integer primary key autoincrement,ip text not null unique);";
        db.execSQL(create);


        initEvent();
        autoConnect();


    }


    private void connectionInformation() {
        new MaterialAlertDialogBuilder(context)
                .setTitle("连接信息")
                .setMessage("IP:" + client.getInetAddress().getHostAddress()
                        + "\n端口:" + client.getPort())
                .setPositiveButton("断开连接", (dialog, which) -> {
                    destroyConnect();
                }).setNegativeButton("重连", (dialog, which) -> {
            addTextItem(true, 1, "重连");
        })
                .setNeutralButton("取消", null)
                .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

    }


    public void setEdit(String text) {
        mChatEdittext.setText(text);
        mChatEdittext.setSelection(text.length());
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// 接受软键盘输入的编辑文本或其它视图
        inputMethodManager.showSoftInput(mChatEdittext, InputMethodManager.SHOW_FORCED);
    }


    final String defaultConfiguration = "关机@重启@注销@休眠@睡眠@锁屏@电脑信息@电脑名称@电脑状态@取剪切板@完全隐藏程序@弹出窗口@清空回收站@打开qq@打开网易云音乐@关闭qq@关闭网易云";

    /**
     * 初始化事件
     */
    private void initEvent() {

        mChip1.setOnClickListener(v -> {
            setEdit("执行:");
        });

        mChip2.setOnClickListener(v -> {
            setEdit("运行:");
        });

        mChip3.setOnClickListener(v -> {
            setEdit("终止:");
        });

        mChip4.setOnClickListener(v -> {
            DialogUtils.showInputDialog2(context
                    , "弹出信息框", "", "请输入文本"
                    , new DialogUtils.OnInputDialog2ButtonListener() {
                        @Override
                        public void confirm(DialogInterface dialog, String content) {
                            if (content.isEmpty()) return;
                            sendText("运行:mshta vbscript:msgbox(\"" + content + "\",64,\"来自" + (isLink?Build.MODEL:"内网广播") + "的消息\")(window.close)");
                            dialog.dismiss();
                        }

                        @Override
                        public void cancel() {

                        }
                    }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_Via);

        });


        mChip4.setOnLongClickListener(v -> {

            String content = DabaiUtils.getClipboardContent(context);
            sendText("运行:mshta vbscript:msgbox(\"" + content + "\",64,\"来自" + Build.MODEL + "的消息\")(window.close)");

            return true;
        });


        mChip5.setOnClickListener(v -> {
            DialogUtils.showInputDialog2(context
                    , "打开网页", "", "请输入网址"
                    , new DialogUtils.OnInputDialog2ButtonListener() {
                        @Override
                        public void confirm(DialogInterface dialog, String content) {
                            if (content.isEmpty()) return;
                            sendText("打开网址:" + content);
                            dialog.dismiss();
                        }

                        @Override
                        public void cancel() {

                        }
                    }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_Via);

        });

        mChip5.setOnLongClickListener(v -> {

            String content = DabaiUtils.getClipboardContent(context);

            Matcher matcher = Patterns.WEB_URL.matcher(content);
            while (matcher.find()) {
                content = matcher.group();
                sendText("打开网址:" + content);

            }

            return true;
        });


        mSendfile.setOnClickListener(v -> {
            initFast();
        });
        mSendfile.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                File configFile = new File(getExternalFilesDir("config"), "config.txt");

                if (!configFile.exists()) {
                    FileUtils.writeText(configFile, defaultConfiguration);
                }

                String baseTools = FileUtils.readText(configFile);

                DialogUtils.showInputDialog2(context, "修改快捷操作配置"
                        , baseTools, "配置文本", new DialogUtils.OnInputDialog2ButtonListener() {
                            @Override
                            public void confirm(DialogInterface dialog, String content) {
                                if (content.isEmpty()) {
                                    return;
                                }
                                FileUtils.writeText(configFile, content);
                                dialog.dismiss();
                            }

                            @Override
                            public void cancel() {

                            }
                        }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_Via);


                return true;
            }
        });

        mRoomname.setOnClickListener(v -> {
            if (client != null) {
                if (!client.isConnected()) {
                    MdcDialog.showConfirmDialog(context, "提示"
                            , "是否重连到 " + client.getInetAddress().getHostAddress() + " ?", new MdcDialog.OnConfirmDialogButtonListener() {
                                @Override
                                public void confirm() {
                                    autoConnect();
                                }

                                @Override
                                public void cancel() {
                                }
                            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
                } else {
                    connectionInformation();
                }
            } else {
                autoConnect();
            }
        });

        chatAdapter = new ChatAdapter(this, R.layout.item_chat);
        linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerview.setLayoutManager(linearLayoutManager);
        //mRecyclerview.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mRecyclerview.setAdapter(chatAdapter);


        mSendtext.setOnClickListener(v -> {
            String content = mChatEdittext.getText().toString();
            if (StringUtils.isEmpty(content)) {
                return;
            }
            sendText(content);

        });
        mSendtext.setOnLongClickListener(v -> {
            sendText(DabaiUtils.getClipboardContent(context));
            return false;
        });

        chatAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            ChatModel chatModel = chatAdapter.getData().get(position);

            new MaterialAlertDialogBuilder(context)
                    .setTitle("内容")
                    .setMessage(chatModel.getContent())
                    .setPositiveButton("确定", null)
                    .setNeutralButton("复制", (dialog, which) -> copyText(context, chatModel.getContent()))
                    .setNegativeButton("+1", (dialog, which) -> sendText(chatModel.getContent()))
                    .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            return true;
        });

        chatAdapter.setOnItemClickListener((adapter, view, position) -> {
            ChatModel chatModel = chatAdapter.getData().get(position);
            String content = chatModel.getContent();

            specialListClickEvent(content);

            if ((System.currentTimeMillis() - itemClickTime) > 400) {
                itemClickTime = System.currentTimeMillis();
            } else {

                View diaView = ViewUtils.inflateLayout(context, R.layout.dialog_detailed_content);
                AlertDialog alertDialog = new MaterialAlertDialogBuilder(context)
                        .setView(diaView)
                        .show();
                alertDialog.getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                TextView textView1 = diaView.findViewById(R.id.textView1);
                textView1.setText(content);

                Button button1 = diaView.findViewById(R.id.button1);
                Button button2 = diaView.findViewById(R.id.button2);

                button1.setOnClickListener(v -> {
                    copyText(context, chatModel.getContent());
                    alertDialog.dismiss();
                });
                button2.setOnClickListener(v -> {
                    sendText(chatModel.getContent());
                    alertDialog.dismiss();
                });

            }

        });


    }


    private void getIntentContent() {

        Intent intent = getIntent();
        try {

            if (intent == null)
                return;
            Bundle extras = intent.getExtras();
            if (extras == null)
                return;

            if ("text/plain".equals(intent.getType())) {//分享的内容类型，如果png图片：image/png

                String text = "" + extras.get(Intent.EXTRA_TEXT);
                if (StringUtils.isEmpty(text)) {
                    DabaiUtils.showToast(this, "异常:空内容!");
                    finish();
                    return;
                }
                Matcher matcher = Patterns.WEB_URL.matcher(text);
                if (matcher.find()) {
                    text = matcher.group();
                    sendText("打开网址:" + text);
                }
            }

        } catch (Exception e) {
            DabaiUtils.showToast(this, "异常:" + e.getMessage());
            Log.d("DBTAG", "onCreate: " + e.getMessage());
            DabaiUtils.backHome(this);
            finish();
        }

    }


    private void specialListClickEvent(String content) {
        if (content.equalsIgnoreCase("已经连接到一对一服务器!")) {
            if (client != null) {
                DBToast.showText(context, "端口:" + client.getPort());
            }
        }
        if (content.equalsIgnoreCase("已经连接到文件服务器!")) {
            if (client2 != null) {
                DBToast.showText(context, "端口:" + client2.getPort());
            }
        }

    }

    private void sendText(String content) {
        addTextItem(true, 1, content);
        mChatEdittext.setText("");

        if (content.equals("重连"))
            return;


        //判断是否通过TCP连接，否则UDP广播
        if (isLink) {


            new Thread(() -> {

                try {
                    OutputStream outputStream = client.getOutputStream();
                    outputStream.write(content.getBytes());
                    outputStream.flush();

                } catch (Exception e) {
                    runOnUiThread(() -> addTextItem(false, 3, "发送失败!"));
                }

            }).start();

        } else {
            new Thread(() -> {
                try {
                    //这里是接收方的端口号
                    byte[] data = content.getBytes();
                    DatagramPacket packet = new DatagramPacket(data, data.length, udpServerAddress, 8881);   //③
                    udpSocket.send(packet);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

        }


    }


    private void addTextItem(boolean isMy, int mode, String content) {

        ChatModel chatModel = new ChatModel();

        switch (mode) {
            case 1:
                //普通
                if (isMy) {
                    chatModel.setGravity(Gravity.END);
                } else {
                    chatModel.setGravity(Gravity.START);

                    if (!isRunForground) {
                        NotificationUtils.notificationText(context, "chat", "聊天通知", R.drawable.ic_stat_link, "来自其他设备的消息"
                                , content);
                    }

                }
                chatModel.setTextIsSelectable(true);

                chatModel.setTextSize(16f);
                chatModel.setTextColor(getResources().getColor(R.color.textColor));

                break;
            case 2:
                //系统消息
                chatModel.setTextSize(12f);
                chatModel.setTextColor(Color.parseColor("#536DFE"));
                chatModel.setGravity(Gravity.CENTER);

                break;
            case 3:
                //错误
                chatModel.setTextSize(12f);
                chatModel.setTextColor(Color.parseColor("#F44336"));
                chatModel.setGravity(Gravity.CENTER);
                break;
            case 4:
                //正确
                chatModel.setTextSize(12f);
                chatModel.setTextColor(Color.parseColor("#4CAF50"));
                chatModel.setGravity(Gravity.CENTER);
                break;
        }

        chatModel.setContent(content);

        chatAdapter.addData(chatModel);
        linearLayoutManager.scrollToPosition(chatAdapter.getData().size() - 1);

        if (isMy) {
            textCmd(content);
        } else {
            textCmd2(content);
        }

    }


    private void textCmd(String text) {
        switch (text) {
            case "重连":
                destroyConnect();
                autoConnect();
                break;
            case "退出":
                finish();
                break;
        }
    }

    private void textCmd2(String text) {
        if (text.equalsIgnoreCase("取剪切板") || text.equalsIgnoreCase("clip")) {
            String con = DabaiUtils.getClipboardContent(context);
            if (!con.equalsIgnoreCase(text)) {
                sendText(con);
            }
        }
        if (text.equalsIgnoreCase("短信")) {

            PermissionX.init(this)
                    .permissions(Manifest.permission.READ_SMS)
                    .request((allGranted, grantedList, deniedList) -> {
                        if (!allGranted) {
                            DabaiUtils.showToast(context, "需要短信权限");
                        } else {

                            String con = getSmsInPhone();
                            if (!con.equalsIgnoreCase(text)) {
                                sendText(con);
                            }

                        }
                    });
        }
    }


    public String getSmsInPhone() {
        final String SMS_URI_ALL = "content://sms/"; // 所有短信
        final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
        final String SMS_URI_SEND = "content://sms/sent"; // 已发送
        final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿
        final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱
        final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败
        final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表

        StringBuilder smsBuilder = new StringBuilder();

        try {
            Uri uri = Uri.parse(SMS_URI_INBOX);
            String[] projection = new String[]{"_id", "address", "person",
                    "body", "date", "type",};
            //Cursor cur = getContentResolver().query(uri, projection, null,
            //        null, "date desc"); // 获取手机内部短信
            // 获取短信中最新的未读短信
            Cursor cur = getContentResolver().query(uri, projection,
                    "read = ?", new String[]{"0"}, "date desc");
            if (cur.moveToFirst()) {
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                do {
                    String strAddress = cur.getString(index_Address);
                    int intPerson = cur.getInt(index_Person);
                    String strbody = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);

                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);

                    String strType = "";
                    if (intType == 1) {
                        strType = "接收";
                    } else if (intType == 2) {
                        strType = "发送";
                    } else if (intType == 3) {
                        strType = "草稿";
                    } else if (intType == 4) {
                        strType = "发件箱";
                    } else if (intType == 5) {
                        strType = "发送失败";
                    } else if (intType == 6) {
                        strType = "待发送列表";
                    } else if (intType == 0) {
                        strType = "所有短信";
                    } else {
                        strType = "null";
                    }


                    smsBuilder.append("发信人:" + strAddress);
                    smsBuilder.append("\n\n" + strbody);
                    smsBuilder.append("\n\n时间:" + strDate);
                } while (cur.moveToNext());

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }
            } else {
                smsBuilder.append("没结果!");
            }

            // smsBuilder.append("getSmsInPhone has executed!");

        } catch (SQLiteException ex) {

        }

        return smsBuilder.toString();
    }


    /**
     * 自动连接
     */
    public void autoConnect() {

        if (SharedPreferencesBasicUse.getString("lastIp", "").equals("")) {
            DBToast.showYellowToast(context, "请点击右上角,进行扫描配对!");
        } else {
            connectServer(SharedPreferencesBasicUse.getString("lastIp", "")
                    , Integer.parseInt(SharedPreferencesBasicUse.getString("lastPort", "")));
        }

        try {
            //自己的发送端口
            udpSocket = new DatagramSocket(8880);  //①
            //对方的ip
            udpServerAddress = InetAddress.getByName("255.255.255.255");  //②

            receiveUdpMessage();
            addTextItem(false, 4, "已经连接到内网广播服务器!");

            if (!isLink){
                getIntentContent();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void connectServer(String ip, int port) {

        addTextItem(false, 2, "正在尝试连接一对一服务器...");
        new Thread(() -> {

            try {
                if (client != null) {
                    if (client.isConnected()) {
                        connectTextServer();
                        runOnUiThread(() -> {
                            mRoomname.setText(client.getInetAddress().getHostAddress());
                            addTextItem(false, 4, "已经连接到一对一服务器!");

                            isLink = true;

                            getIntentContent();

                            ContentValues in = new ContentValues();
                            in.put("ip", ip);
                            db.insert("IpRecord", null, in);

                        });
                        return;
                    }
                }
                client = new Socket(ip
                        , port);

                // client.setSoTimeout(5000);
                client.setKeepAlive(true);

                connectTextServer();

                runOnUiThread(() -> {
                    mRoomname.setText(client.getInetAddress().getHostAddress());
                    addTextItem(false, 4, "已经连接到一对一服务器!");
                    //connectFileServer(ip, port);
                    isLink = true;

                    getIntentContent();


                    ContentValues in = new ContentValues();
                    in.put("ip", ip);
                    db.insert("IpRecord", null, in);
                });

            } catch (IOException e) {
                runOnUiThread(() -> {
                    addTextItem(false, 3, "连接一对一服务器失败!");
                });
            }

        }).start();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 101) {
                if (data != null) {


                    try {
                        String link = QRCodeUtils.getQrCodeScannerResult(data);

                        if (!link.startsWith("scf2f://sc/?ip=")) {
                            throw new Exception("此二维码连接协议不正确,请扫描简连生成的二维码!");
                        }

                        Uri mUri = Uri.parse(link);

                        //二维码扫描后 确认界面
                        MdcDialog.showConfirmDialog(context, "提示"
                                , "确定连接 " + mUri.getQueryParameter("ip") + " 嘛?"
                                , new MdcDialog.OnConfirmDialogButtonListener() {
                                    @Override
                                    public void confirm() {

                                        connectServer(mUri.getQueryParameter("ip")
                                                , Integer.parseInt(mUri.getQueryParameter("port")));
                                        SharedPreferencesBasicUse.setString("lastIp", mUri.getQueryParameter("ip"));
                                        SharedPreferencesBasicUse.setString("lastPort", mUri.getQueryParameter("port"));


                                        ContentValues in = new ContentValues();
                                        in.put("ip", mUri.getQueryParameter("ip"));
                                        db.insert("IpRecord", null, in);

                                    }

                                    @Override
                                    public void cancel() {
                                    }
                                });
                    } catch (Exception e) {
                        addTextItem(false, 3, "请扫描正确的连接码!");
                        DabaiUtils.showDialog(context, "请扫描正确的连接码!")
                                .getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
                    }


                }
            }


            if (requestCode == 201) {
                if (data != null) {

                    List<String> mSelected = Matisse.obtainPathResult(data);


                    TipAlertDialog.getInstance(context).showTipLayout("正在载入源文件...");

                    new Thread(() -> {

                        ArrayList<File> files = new ArrayList<>();
                        for (String path : mSelected) {
                            files.add(new File(path));
                        }

                        File tagFile = new File(FileUtils.getDir(context.getExternalCacheDir()), DateUtils.getNowTime(3) + ".zip");

                        //todo 压缩
                        try {
                            new ZipFile(tagFile).addFiles(files);
                        } catch (ZipException e) {
                            e.printStackTrace();
                        }
                        runOnUiThread(() -> {
                            //todo 发送
                            SendFileUtils.sendFile(this, client2, tagFile);
                        });
                    }).start();

                }
            }

            if (requestCode == 301) {
                if (data != null) {

                    String link = data.getStringExtra("link");
                    sendText("打开网址:" + link);

                }
            }
        }

    }


    public void initFast() {

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        //imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        imm.hideSoftInputFromWindow(mChatEdittext.getWindowToken(), 0);


        File configFile = new File(getExternalFilesDir("config"), "config.txt");

        if (!configFile.exists()) {
            FileUtils.writeText(configFile, defaultConfiguration);
        }

        String baseTools = FileUtils.readText(configFile);

        String[] tools = baseTools.split("@");


        View view1 = ViewUtils.inflateLayout(context, R.layout.item_cloud_category);
        BottomSheetDialog cateDialog = new BottomSheetDialog(context);
        cateDialog.setTitle("分类");
        cateDialog.setContentView(view1);
        cateDialog.show();
        cateDialog.getWindow().setWindowAnimations(R.style.DBAnim_Transitions_Via);

        ChipGroup chipGroup = view1.findViewById(R.id.chipGroup);


        for (String str : tools) {

            Chip chip = new Chip(context);
            chip.setText(str);


            chip.setOnClickListener(v -> {
                cateDialog.dismiss();

                if (str.contains("关机") || str.contains("重启")
                        || str.contains("注销") || str.contains("睡眠")
                        || str.contains("锁屏") || str.contains("休眠")) {

                    MdcDialog.showConfirmDialog(context
                            , "提示", "确定 " + str + " ?", new MdcDialog.OnConfirmDialogButtonListener() {
                                @Override
                                public void confirm() {
                                    sendText(str);
                                }

                                @Override
                                public void cancel() {
                                }
                            });
                } else {
                    sendText(str);
                }

            });

            chipGroup.addView(chip);
        }

    }



    /**
     * 复制文本
     *
     * @param context 上下文
     * @param text    文本
     */
    public static void copyText(Context context, String text) {
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mclipData = ClipData.newPlainText("DABAI", text);
        clipboardManager.setPrimaryClip(mclipData);
        DabaiUtils.showToast(context,"复制成功");
    }
    /**
     * 复制文本
     *
     * @param context 上下文
     * @param text    文本
     */
    public static void copyText(Context context, String text,String tip) {
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mclipData = ClipData.newPlainText("DABAI", text);
        clipboardManager.setPrimaryClip(mclipData);
        DabaiUtils.showToast(context,tip);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();

        if (itemId == R.id.down) {
            copyText(context, "0000","密码已复制");
            DabaiUtils.openLink(context, "https://dabai2017.lanzouy.com/b07bdg94b");

        }
        if (itemId == R.id.fastTool) {
            initFast();
        }
        if (itemId == R.id.qr_scan) {

            if (client != null) {
                //DBToast.showYellowToast(context,"请先断开连接!");
                connectionInformation();
                return true;
            }

            new MaterialAlertDialogBuilder(context)
                    .setItems(new String[]{"手动输入地址", "扫码连接", "历史连接记录"}, (dialog, which) -> {
                        if (which == 2) {

                            ArrayList<String> arrayList = new ArrayList<>();

                            String search = "select * from IpRecord";
                            Cursor cursor = db.rawQuery(search, null);

                            while (cursor.moveToNext()) {
                                String text = cursor.getString(cursor.getColumnIndex("ip"));
                                arrayList.add(text);
                            }
                            cursor.close();

                            if (arrayList.isEmpty()) {
                                return;
                            }

                            String[] items = arrayList.toArray(new String[0]);

                            new MaterialAlertDialogBuilder(context)
                                    .setTitle("连接记录")
                                    .setItems(items, (dialogInterface, i) -> {
                                        connectServer(items[i]
                                                , 8877);

                                    })
                                    .setPositiveButton("确认", null)
                                    .show().getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);

                        }
                        if (which == 0) {

                            DialogUtils.showInputDialog(context, "连接设备"
                                    , SharedPreferencesBasicUse.getString("lastIp", "192.168.1.1")
                                    , SharedPreferencesBasicUse.getString("lastPort", "8877")
                                    , new DialogUtils.OnInputDialogButtonListener() {
                                        @Override
                                        public void confirm(AlertDialog dialog, String text1, String text2) {
                                            if (text1.length() < 7 || text2.isEmpty()) {
                                                DBToast.showText(context, "请正确输入IP地址和端口!", false);
                                                return;
                                            }
                                            connectServer(text1
                                                    , Integer.parseInt(text2));
                                            SharedPreferencesBasicUse.setString("lastIp", text1);
                                            SharedPreferencesBasicUse.setString("lastPort", text2);
                                            dialog.dismiss();
                                        }

                                        @Override
                                        public void cancel() {
                                        }
                                    }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                        }
                        if (which == 1) {
                            QRCodeUtils.startQrCodeScanner(MainActivity.this, 101);
                        }
                    })
                    .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 连接接收服务器
     */
    private void connectTextServer() {

        new Thread(() -> {
            try {

                do {
                    DataInputStream dataInputStream = new DataInputStream(client.getInputStream());
                    while (true) {
                        byte[] data = new byte[1024 * 10];
                        int len;
                        if ((len = dataInputStream.read(data)) != -1) {
                            String content = new String(data, 0, len);
                            runOnUiThread(() -> {
                                addTextItem(false, 1, content);
                            });
                        }
                    }

                } while (client != null);

            } catch (Exception e) {
                runOnUiThread(() -> addTextItem(false, 3, "一对一服务器连接断开"));
            }

        }).start();


    }

    private void receiveUdpMessage() {

        new Thread(() -> {
            try {
                //若发送消息，则使用8888端口

                DatagramSocket socket = new DatagramSocket(8882);

                while (true) {

                    byte[] data = new byte[1024 * 10];
                    DatagramPacket packet = new DatagramPacket(data, data.length);
                    socket.receive(packet);
                    String content = new String(packet.getData(), packet.getOffset(), packet.getLength());

                    runOnUiThread(() -> {
                        addTextItem(false, 1, content);
                    });
                }

            } catch (Exception e) {
                runOnUiThread(() -> addTextItem(false, 3, "广播服务器连接断开"));
            }
        }).start();
    }


    private void connectFileServer() {

        new Thread(() -> {
            try {

                do {
                    DataInputStream dataInputStream = new DataInputStream(client2.getInputStream());
                    FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/a.zip");
                    while (true) {
                        byte[] data = new byte[1024];
                        int len;
                        if ((len = dataInputStream.read(data)) != -1) {
                            fileOutputStream.write(data, 0, len);
                            fileOutputStream.flush();
                        }
                    }


                } while (client2 != null);

            } catch (Exception e) {
                runOnUiThread(() -> addTextItem(false, 3, "一对一服务器连接错误:" + e.getMessage()));
            }

        }).start();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void initViews() {
        mRoomname = findViewById(R.id.roomName);
        mChatEdittext = findViewById(R.id.chat_editText);
        mSendtext = findViewById(R.id.sendText);
        mRecyclerview = findViewById(R.id.recyclerView);
        mSendfile = findViewById(R.id.sendFile);
        mChip1 = findViewById(R.id.chip1);
        mChip2 = findViewById(R.id.chip2);
        mChip3 = findViewById(R.id.chip3);
        mChip4 = findViewById(R.id.chip4);
        mChip5 = findViewById(R.id.chip5);
    }


    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    private void destroyConnect() {
        isLink = false;
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (client.isClosed()) {
                client = null;
                mRoomname.setText("未连接");
            }
        }
        if (client2 != null) {
            try {
                client2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (client2.isClosed()) {
                client2 = null;
            }
        }
    }

    @Override
    protected void onDestroy() {
        destroyConnect();
        super.onDestroy();
    }
}